﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using System.Data.Objects;

namespace Library
{
    public partial class BookViewForm : Form
    {
        public Book book = new Book();
        bool add = false;
        LibraryEntities1 ins = new LibraryEntities1();
        public static ObjectSet<BookType> bookTypes;
        public static ObjectSet<Author> authors;
        public static ObjectSet<Book> books;
        public static ObjectSet<InstanceBook> instanceBooks;

        List<InstanceBook> InstToAdd = new List<InstanceBook>();
        List<InstanceBook> InstToDel = new List<InstanceBook>();

        public BookViewForm(Book book, bool add)
        {
            InitializeComponent();
            this.book = book;
            this.add = add;
            bookTypes = ins.BookType;
            books = ins.Book;
            authors = ins.Author;
            instanceBooks = ins.InstanceBook;

            if (book != null)
            {
                TBName.Text = book.BookName;
                TBISBN.Text = book.ISBN;
                TBLocation.Text = book.Location;
            }

        }

        //public void GetInfoBook()
        //{
        //    string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.LibraryConnectionString"].ConnectionString;
        //    SqlConnection conn = new SqlConnection();
        //    conn.ConnectionString = connectionString;
        //    SqlCommand myCommand = conn.CreateCommand();
        //    myCommand.CommandType = CommandType.StoredProcedure;
        //    myCommand.CommandText = "[getBookbyISBN]";
        //    conn.Open();

        //    myCommand.Parameters.Add("@ISBN", SqlDbType.NVarChar, 50);
        //    myCommand.Parameters["@ISBN"].Value = ISBN;
        //    SqlDataReader dataReader = myCommand.ExecuteReader();
        //    dataReader.Read();
        //    name = dataReader.GetString(0);
        //    location = dataReader.GetString(2);

        //    TBName.Text = name;
        //    TBISBN.Text = ISBN;
        //    TBLocation.Text = location;
        //}


        //public void GetAuthors()
        //{
        //    authors = String.Empty;
        //    string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.LibraryConnectionString"].ConnectionString;
        //    SqlConnection conn = new SqlConnection();
        //    conn.ConnectionString = connectionString;
        //    SqlCommand myCommand = conn.CreateCommand();
        //    myCommand.CommandType = CommandType.StoredProcedure;
        //    myCommand.CommandText = "[getAuthorsbyISBN]";
        //    conn.Open();

        //    myCommand.Parameters.Add("@ISBN", SqlDbType.NVarChar, 50);
        //    myCommand.Parameters["@ISBN"].Value = ISBN;
        //    SqlDataReader dataReader = myCommand.ExecuteReader();
        //    string authorSurname = string.Empty;
        //    string authorName = string.Empty;
        //    string authorPatronymic = string.Empty;
        //    while (dataReader.Read())
        //    {
        //        authorSurname = dataReader.GetString(0);
        //        authorName = dataReader.GetString(1);
        //        authorPatronymic = dataReader.GetString(2);

        //        if (authorName != string.Empty)
        //            authorName = authorName.Substring(0, 1);

        //        if (authorPatronymic != string.Empty)
        //            authorPatronymic = authorPatronymic.Substring(0, 1);


        //        authors +=  string.Format("{0} {1}.{2}., ",authorSurname, authorName, authorPatronymic);
        //    }
        //    if (authors!=string.Empty)
        //        authors = authors.Substring(0, authors.Length - 2);
        //    TBAuthors.Text = authors;
        //}

        //public void GetInstances()
        //{
           
        //    string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.LibraryConnectionString"].ConnectionString;
        //    SqlConnection conn = new SqlConnection();
        //    conn.ConnectionString = connectionString;
        //    SqlCommand myCommand = conn.CreateCommand();
        //    myCommand.CommandType = CommandType.StoredProcedure;
        //    myCommand.CommandText = "[getInstancesbyISBN]";
        //    conn.Open();

        //    myCommand.Parameters.Add("@ISBN", SqlDbType.NVarChar, 50);
        //    myCommand.Parameters["@ISBN"].Value = ISBN;
        //    SqlDataReader dataReader = myCommand.ExecuteReader();

        //    while (dataReader.Read())
        //    {
        //        listBox1.Items.Add(dataReader.GetString(0));
        //    }
        //}

        //public void GetTypes ()
        //{
           
        //    string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.LibraryConnectionString"].ConnectionString;
        //    SqlConnection conn = new SqlConnection();
        //    conn.ConnectionString = connectionString;
        //    SqlCommand myCommand = conn.CreateCommand();
        //    myCommand.CommandType = CommandType.StoredProcedure;
        //    myCommand.CommandText = "[getAllTypes]";
        //    conn.Open();

        //    SqlDataReader dataReader = myCommand.ExecuteReader();
        //    while (dataReader.Read())
        //    {
        //        CBBookType.Items.Add(dataReader.GetString(0));
        //    }
        //}


        //public void GetBookTypeName()
        //{
        //    GetTypes();
        //    string connectionString = ConfigurationManager.ConnectionStrings["Library.Properties.Settings.LibraryConnectionString"].ConnectionString;
        //    SqlConnection conn = new SqlConnection();
        //    conn.ConnectionString = connectionString;
        //    SqlCommand myCommand = conn.CreateCommand();
        //    myCommand.CommandType = CommandType.StoredProcedure;
        //    myCommand.CommandText = "[getTypebyISBN]";
        //    conn.Open();

        //    myCommand.Parameters.Add("@ISBN", SqlDbType.NVarChar, 50);
        //    myCommand.Parameters["@ISBN"].Value = ISBN;
        //    SqlDataReader dataReader = myCommand.ExecuteReader();

        //    dataReader.Read();
        //    CBBookType.SelectedItem  = dataReader.GetString(0);
        //    CBBookType.SelectedItem = dataReader.GetString(0);
        //    CBBookType.SelectedText = dataReader.GetString(0);
        //    CBBookType.Text = dataReader.GetString(0);
        //    int a =  CBBookType.Items.Count;
         
        //}

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BookViewForm_Load(object sender, EventArgs e)
        {
            foreach (var x in bookTypes)
            {
                CBBookType.Items.Add(x.TypeName);
            }

            CBBookType.SelectedIndex = 0;

            if (book != null)
            {
                CBBookType.SelectedItem = book.BookType1.TypeName;
                CBBookType.SelectedItem = book.BookType1.TypeName;
                CBBookType.SelectedText = book.BookType1.TypeName;
                CBBookType.Text = book.BookType1.TypeName;

                string authors = String.Empty;
                string authorName = String.Empty;
                string authorPatronymic = String.Empty;
                foreach (var x in book.BookAuthor)
                {
                    authorName = x.Author.Name;
                    authorPatronymic = x.Author.Patronymic;

                    if (authorName != string.Empty)
                        authorName = authorName.Substring(0, 1);

                    if (authorPatronymic != string.Empty)
                        authorPatronymic = authorPatronymic.Substring(0, 1);
                    authors += string.Format("{0} {1}.{2}., ", x.Author.Surname, authorName, authorPatronymic);

                }
                if (authors != string.Empty)
                    authors = authors.Substring(0, authors.Length - 2);
                TBAuthors.Text = authors;


                bookView.Columns.Add("instanceId", "instanceId");
                bookView.Columns["instanceId"].Visible = false;

                bookView.Columns.Add("InventoryNumber", "Инвентарный номер");
                bookView.Columns["InventoryNumber"].ReadOnly = true;
                bookView.Columns["InventoryNumber"].Width = 210;

                bookView.Columns.Add("Control", "Контрольный");
                bookView.Columns["Control"].Width = 150;

                int i = 0;
                foreach (var x in book.InstanceBook)
                {
                    bookView.Rows.Add();
                    bookView.Rows[i].Cells[0].Value = x.invetoryId;
                    bookView.Rows[i].Cells[1].Value = x.InventoryNumber;
                    if (Convert.ToBoolean(x.Control))
                        bookView.Rows[i].Cells[2].Value = "Контрольный";
                    else
                        bookView.Rows[i].Cells[2].Value = "Доступный";
                    i++;
                }



            }
            else
            {
                button1.Enabled = false;
                button4.Enabled = false;
                button5.Enabled = false;
            }
            //GetInfoBook();
            //GetAuthors();
            //GetInstances();
            //GetTypes();
            //GetBookTypeName();
        }

        public void getAuthors(Book book)
        {
            string authors = String.Empty;
            string authorName = String.Empty;
            string authorPatronymic = String.Empty;
            foreach (var x in book.BookAuthor)
            {
                authorName = x.Author.Name;
                authorPatronymic = x.Author.Patronymic;

                if (authorName != string.Empty)
                    authorName = authorName.Substring(0, 1);

                if (authorPatronymic != string.Empty)
                    authorPatronymic = authorPatronymic.Substring(0, 1);
                authors += string.Format("{0} {1}.{2}., ", x.Author.Surname, authorName, authorPatronymic);

            }
            if (authors != string.Empty)
                authors = authors.Substring(0, authors.Length - 2);
            TBAuthors.Text = authors;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (book == null)
                book = new Book();
            else
                book = books.Where(x => x.ISBN.Equals(TBISBN.Text)).FirstOrDefault();
          
            book.ISBN = TBISBN.Text;
            book.BookName = TBName.Text;
            book.Location = TBLocation.Text;

            BookType type = bookTypes.Where(x=>x.TypeName == CBBookType.SelectedItem).FirstOrDefault();
            book.BookType1 = type;

         

            if (add)
            {
                ins.AddToBook(book);
            }
            ins.SaveChanges();

            foreach (DataGridViewRow row in bookView.Rows)
            {
                string inventoryNumber = row.Cells[1].Value.ToString();
                InstanceBook instB = instanceBooks.Where(x => x.InventoryNumber == inventoryNumber).FirstOrDefault();
                instB.bookid = book.bookid;
                ins.SaveChanges();
            }
           

            this.Close();
 
           
        }

        private void button5_Click(object sender, EventArgs e)
        {
            AuthorBookView fm = new AuthorBookView(book);
            fm.ShowDialog();
            books = ins.Book;
            book = books.Where(x => x.bookid == book.bookid).FirstOrDefault();
            getAuthors(book);

        }

        private void button1_Click(object sender, EventArgs e)
        {

            InstanceViewForm fm = new InstanceViewForm(null, true, bookView.Rows);
            fm.ShowDialog();
            if (fm.instance!=null)
            {
                bookView.Rows.Add();
                InstToAdd.Add(fm.instance);

                bookView.Rows[bookView.Rows.Count - 1].Cells[0].Value = fm.instance.invetoryId;
                bookView.Rows[bookView.Rows.Count - 1].Cells[1].Value = fm.instance.InventoryNumber;
                if (Convert.ToBoolean(fm.instance.Control))
                    bookView.Rows[bookView.Rows.Count - 1].Cells[2].Value = "Контрольный";
                else
                    bookView.Rows[bookView.Rows.Count - 1].Cells[2].Value = "Доступный";

                ins.AddToInstanceBook(fm.instance);
                ins.SaveChanges();
            }
            
        }

        private void button4_Click(object sender, EventArgs e)
        {

            if (bookView.CurrentRow != null)
            {
                
                int elementId = Convert.ToInt32(bookView.CurrentRow.Cells[0].Value);
                if (instanceBooks.Where(x => x.invetoryId == elementId).Count() == 1)
                {
                    InstanceBook element = instanceBooks.Where(x => x.invetoryId == elementId).FirstOrDefault();
                    if (element.Reader != null)
                        MessageBox.Show("Невозможно удаление. Книга выдана читателю");
                    else
                    {
                        instanceBooks.DeleteObject(element);
                        ins.SaveChanges();
                        bookView.Rows.Remove(bookView.CurrentRow);
                    }
                }
                else
                    bookView.Rows.Remove(bookView.CurrentRow);

            }
            else
            {
                MessageBox.Show("Выберите строку для удаления");
            }

        }
    }
}
